package com.dshore.messagecenter.util;

import org.nutz.http.Http;
import org.nutz.http.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dshore.messagecenter.model.AddressEntity;
import com.google.common.base.Preconditions;

public class MapUtil {
   private static final Logger log = LoggerFactory.getLogger(MapUtil.class);
   private static final String AK = "oNQFWrFaz3iGCIGcvfvOCctR";
   private static final String FORMAT = "http://api.map.baidu.com/location/ip?ak={}&ip={}&coor=bd09ll";

   public static AddressEntity ipToAddress(String ip) {
      if (StringUtils.isEmpty(ip)) {
         return null;
      } else {
         log.info("convert ip to location, ip:{}", ip);

         try {
            Response response = Http.get(MessageFormatter.format("http://api.map.baidu.com/location/ip?ak={}&ip={}&coor=bd09ll", "oNQFWrFaz3iGCIGcvfvOCctR", ip).getMessage());
            if (response.isOK()) {
               String body = response.getContent();
               JSONObject json = (JSONObject)JSON.parse(body);
               if (json.containsKey("status")) {
                  int status = json.getInteger("status");
                  Preconditions.checkArgument(status == 0, "返回状态不正确, status=" + status);
                  JSONObject content = json.getJSONObject("content");
                  JSONObject addressDetail = content.getJSONObject("address_detail");
                  AddressEntity address = new AddressEntity();
                  String province = addressDetail.getString("province");
                  Integer cityCode = addressDetail.getInteger("city_code");
                  String city = addressDetail.getString("city");
                  String district = addressDetail.getString("district");
                  address.setProvince(province);
                  address.setCityCode(cityCode);
                  address.setCity(city != null ? city : province);
                  address.setDistrict(district);
                  JSONObject point = content.getJSONObject("point");
                  address.setLng(point.getDouble("x"));
                  address.setLat(point.getDouble("y"));
                  return address;
               }
            }

            return null;
         } catch (RuntimeException var13) {
            log.error("error parse from ip:{}, error:{}", ip, var13);
            throw new RuntimeException("获取地址异常");
         }
      }
   }

   public static void main(String[] args) {
      String ip = "115.236.29.18";
      System.out.println(ipToAddress(ip));
   }
}
